var AjaxRequest = function(url, data, cb) {
    $.ajax({
        url:url,
        dataType:'json',
        data:data,
        type:'POST',
        success:function(json) {
            cb(json);
        }
    });
};
$.fn.serializeJSON = function() {
    var json = {};
    jQuery.map($(this).serializeArray(), function(n, i) {
        if(json[n['name']] == null) {
            json[n['name']] = n['value'];
        } else {
            var tmp = json[n['name']];
            if(tmp instanceof Array) {
                tmp.push(n['value']);
                json[n['name']] = tmp;
            } else {
                var t = [];
                t.push(tmp);
                t.push(n['value']);
                json[n['name']] = t;
            }
        }

    });
    return json;
};
jQuery.cookie = function(G, H, L) {
    if (typeof H != "undefined") {
        L = L || {};
        if (H === null) {
            H = "";
            L.expires = -1
        }
        var F = "";
        if (L.expires && (typeof L.expires == "number" || L.expires.toUTCString)) {
            var B;
            if (typeof L.expires == "number") {
                B = new Date();
                B.setTime(B.getTime() + (L.expires * 24 * 60 * 60 * 1000))
            } else B = L.expires;
            F = "; expires=" + B.toUTCString()
        }
        var I = L.path ? "; path=" + L.path : "",
                J = L.domain ? "; domain=" + L.domain : "",
                A = L.secure ? "; secure" : "";
        document.cookie = [G, "=", encodeURIComponent(H), F, I, J, A].join("")
    } else {
        var C = null;
        if (document.cookie && document.cookie != "") {
            var K = document.cookie.split(";");
            for (var D = 0; D < K.length; D++) {
                var E = jQuery.trim(K[D]);
                if (E.substring(0, G.length + 1) == (G + "=")) {
                    C = decodeURIComponent(E.substring(G.length + 1));
                    break
                }
            }
        }
        return C
    }
};

Date.prototype.format = function(format) {
    var o = {
        "M+" : this.getMonth() + 1, //month
        "d+" : this.getDate(), //day
        "h+" : this.getHours(), //hour
        "m+" : this.getMinutes(), //minute
        "s+" : this.getSeconds(), //second
        "q+" : Math.floor((this.getMonth() + 3) / 3), //quarter
        "S" : this.getMilliseconds() //millisecond
    };
    if (/(y+)/.test(format))
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(format))
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    return format;
};
Date.parse = function(value) {
    var dt = new Date(value);
    return dt.format('yyyy-MM-dd hh:mm:ss');
};

function AjaxPage(config) {
    this.tpl = TrimPath.parseTemplate(config.tpl || '');
    this.pageNo = 1;
    this.url = config.url || window.location.href;
    this.cb = config.cb || undefined;
    this.ct = config.ct;// 内容的容器
    this.pageBar = '#' + config.page.ct;
    this.pageOpts = config.page.params || {};
    this.init(config);
    delete config;
}

AjaxPage.prototype = (function() {
    var sendRequest = function(_self) {
        _self.params.pn = _self.pageNo;
        _self.params.dt = Math.random();
        $.ajax({
            type:'POST',
            url:_self.url,
            dataType:'json',
            data:_self.params,
            success:function(page) {
                maxentries = page.totalCount;// 总记录数
                drawLinks(_self.pageNo - 1, maxentries, _self.opts, _self.panel, _self);
                if (_self.cb) {
                    _self.cb(_self, page);
                } else {
                    var result = _self.tpl.process(page);
                    $('#' + _self.ct).html(result);
                    delete result;
                }
            }
        });
    };

    /**
     * 分页链接事件处理函数
     * @参数 {int} page_id 为新页码
     */
    function pageSelected(page_id, evt) {
        current_page = page_id;
        drawLinks();
        var continuePropagation = opts.callback(page_id, panel);
        if (!continuePropagation) {
            if (evt.stopPropagation) {
                evt.stopPropagation();
            }
            else {
                evt.cancelBubble = true;
            }
        }
        return continuePropagation;
    }

    /**
     * 计算最大分页显示数目
     */
    function numPages(maxentries, opts) {
        return Math.ceil(maxentries / opts.items_per_page); //返回大于等于x的最小整数 
    }

    /**
     * 极端分页的起始和结束点，这取决于current_page 和 num_display_entries.
     * @返回 {数组(Array)}
     */
    function getInterval(current_page, maxentries, opts) {
        var ne_half = Math.ceil(opts.num_display_entries / 2);
        var np = numPages(maxentries, opts);
        var upper_limit = np - opts.num_display_entries;
        var start = current_page > ne_half ? Math.max(Math.min(current_page - ne_half, upper_limit), 0) : 0;
        var end = current_page > ne_half ? Math.min(current_page + ne_half, np) : Math.min(opts.num_display_entries, np);
        return [start,end];
    }

    /**
     * 此函数将分页链接插入到容器元素中
     */
    function drawLinks(current_page, maxentries, opts, panel, _self) {
        panel.empty();
        var interval = getInterval(current_page, maxentries, opts);
        var np = numPages(maxentries, opts);
        // 这个辅助函数返回一个处理函数调用有着正确page_id的pageSelected。
        var getClickHandler = function(page_id) {
            return function(evt) {
                _self.goPage(page_id + 1, evt);
                return false;
            };
        };
        //辅助函数用来产生一个单链接(如果不是当前页则产生span标签)
        var appendItem = function(page_id, appendopts) {
            page_id = page_id < 0 ? 0 : (page_id < np ? page_id : np - 1); // 规范page id值
            appendopts = jQuery.extend({text:page_id + 1, classes:""}, appendopts || {});
            if (page_id == current_page) {
                var lnk = jQuery("<span class='current'>" + (appendopts.text) + "</span>");
            } else {
                var lnk = jQuery("<a>" + (appendopts.text) + "</a>")
                        .bind("click", getClickHandler(page_id))
                        .attr('href', opts.link_to.replace(/__id__/, page_id));
            }
            if (appendopts.classes) {
                lnk.addClass(appendopts.classes);
            }
            panel.append(lnk);
        };
        // 产生"Previous"-链接
        if (opts.prev_text && (current_page > 0 || opts.prev_show_always)) {
            appendItem(current_page - 1, {text:opts.prev_text, classes:"prev"});
        }
        // 产生起始点
        if (interval[0] > 0 && opts.num_edge_entries > 0) {
            var end = Math.min(opts.num_edge_entries, interval[0]);
            for (var i = 0; i < end; i++) {
                appendItem(i);
            }
            if (opts.num_edge_entries < interval[0] && opts.ellipse_text) {
                jQuery("<span>" + opts.ellipse_text + "</span>").appendTo(panel);
            }
        }
        // 产生内部的些链接
        for (var i = interval[0]; i < interval[1]; i++) {
            appendItem(i);
        }
        // 产生结束点
        if (interval[1] < np && opts.num_edge_entries > 0) {
            if (np - opts.num_edge_entries > interval[1] && opts.ellipse_text) {
                jQuery("<span>" + opts.ellipse_text + "</span>").appendTo(panel);
            }
            var begin = Math.max(np - opts.num_edge_entries, interval[1]);
            for (var i = begin; i < np; i++) {
                appendItem(i);
            }

        }
        // 产生 "Next"-链接
        if (opts.next_text && (current_page < np - 1 || opts.next_show_always)) {
            appendItem(current_page + 1, {text:opts.next_text, classes:"next"});
        }
    }

    return{
        init: function(cfg) {
            this.opts = jQuery.extend({
                items_per_page:10,
                num_display_entries:10,
                current_page:0,
                num_edge_entries:0,
                link_to:"#",
                prev_text:"Prev",
                next_text:"Next",
                ellipse_text:"...",
                prev_show_always:true,
                next_show_always:true,
                callback:function() {
                    return false;
                }
            }, cfg.page || {});
            this.panel = jQuery('#' + cfg.page.panel);
            this.params = {};
            if (cfg.params) {
                for (param in cfg.params) {
                    this.params[param] = cfg.params[param];
                }
            }
        },
        goPage:function(pageNo) {
            var _self = this;
            _self.pageNo = pageNo;
            sendRequest(_self);
        }
    };
})();


AreaSelect = function(province, area, city) {
    this.province = $('#' + province);
    this.area = $('#' + area);
    this.city = $('#' + city);
    this.initProvince();
}
AreaSelect.PURL = path + '/area/get';
AreaSelect.AURL = path + '/area/get';
AreaSelect.CURL = path + '/area/get';
AreaSelect.prototype = {
    initProvince:function(cb) {
        var _self = this;
        AjaxRequest(AreaSelect.PURL, {tp:0}, function(areas) {
            for (var i = 0; i < areas.length; i++) {
                $('<option />').attr('value', areas[i].c).text(areas[i].n).appendTo(_self.province);
            }
            _self.province.change(function(e) {
                _self.city.text('');
                _self.selArea($(this).val());
            })
            if(cb)  cb();
        })
    },

    selArea: function(pid,cb) {
        var _self = this;
        if (pid != '') {
            AjaxRequest(AreaSelect.AURL, {tp:1, pid:pid}, function(areas) {
                var sel = $('<select/>');
                $('<option value="">请选择</option>').appendTo(sel);
                for (var i = 0; i < areas.length; i++) {
                    $('<option />').attr('value', areas[i].c).text(areas[i].n).appendTo(sel);
                }
                _self.area.text('');
                sel.appendTo(_self.area);
                sel.change(function() {
                    _self.selCity($(this).val());
                });
                if(cb){
                    cb();
                }
            })
        }
    },

    selCity:function(pid, cb) {
        var _self = this;
        if (pid != '') {
            AjaxRequest(AreaSelect.CURL, {tp:2, pid:pid}, function(cities) {
                _self.city.text('');
                if (cities.length > 0) {
                    var sel = $('<select/>');
                    $('<option value="">请选择</option>').appendTo(sel);
                    for (var i = 0; i < cities.length; i++) {
                        $('<option />').attr('value', cities[i].c).text(cities[i].n).appendTo(sel);
                    }
                    sel.appendTo(_self.city);
                    if(cb) cb();
                }
            })
        }
    },

    value: function() {
        var value = '', control;
        value += this.province.val();
        control = this.area.find('select');
        if (control.length > 0 && control.val() != '') {
            value += ':' + control.val();
            control = this.city.find('select');
            if (control.length > 0 && control.val() != '') {
                value += ':' + control.val();
                delete control;
            }
        }
        return value;
    },
    init:function(value) {
        if(value == null) return;
        var _self  = this;
        var area = value.split(':');
        if(area.length > 1) {
            var p, a, c;
            p = area[0];
            a = area[1];
            if(area.length = 3) c = area[2];

            this.initProvince(function(){
                _self.province.val(p);
            });
            this.selArea(p, function(){
                _self.area.find('select').val(a);
            });

            if(c != null) {
                _self.selCity(a, function(){
                    _self.city.find('select').val(c);
                });
            }
        }
    }
}
var Education = {
    '1':'大专',
    '2':'本科',
    '3':'硕士',
    '4':'博士',
    '5':'博士后',
    '6':'海归'
}
/**
 * 授课方式
 */
var TeachWay = {
    '1':'教师上门',
    '2':'学生上门',
    '3':'双方协商'
}
function getTeachWay(code) {
    return TeachWay[code];
}

/**
 * 上课时间
 */
var Schedule = {
    '11':'星期一上午',
    '12':'星期一下午',
    '13':'星期一晚上'
}
function getSchedule(code) {
    return Schedule[code];
}
/**
 * 所授课程
 */
var G_Course = {
    '1':'小学奥数',
    '2':'小学数学',
    '3':'小学英语',
    '4':'小学语文',
    '5':'初中奥数',
    '6':'初一初二英语',
    '7':'初一初二数学',
    '8':'初一初二化学',
    '9':'初一初二物理',
    '10':'初一初二语文',
    '11':'初三英语',
    '12':'初三数学',
    '13':'初三物理',
    '14':'初三化学',
    '15':'初三语文',
    '16':'初中历史',
    '17':'初中地理',
    '18':'中考心里辅导',
    '19':'高中奥数',
    '20':'高一高二英语',
    '21':'高一高二数学',
    '22':'高一高二物理',
    '23':'高一高二化学',
    '24':'高一高二语文',
    '25':'高三英语',
    '26':'高三数学',
    '27':'高三物理',
    '28':'高三化学',
    '29':'高三语文',
    '30':'高中历史',
    '31':'高中地理',
    '32':'高考心里辅导',
    '33':'上海话',
    '34':'英语口语',
    '35':'新概念英语',
    '36':'牛津英语',
    '37':'托福',
    '38':'雅思',
    '39':'商务英语',
    '40':'日语',
    '41':'韩语',
    '42':'德语',
    '43':'法语',
    '44':'意大利语',
    '45':'西班牙语',
    '46':'阿拉伯语',
    '47':'俄语',
    '48':'葡萄牙语',
    '49':'钢琴',
    '50':'电子琴',
    '51':'小提琴',
    '52':'小号',
    '53':'芭蕾舞',
    '54':'吉它',
    '55':'民族舞',
    '56':'单簧管',
    '57':'萨克斯',
    '58':'声乐',
    '59':'大号',
    '60':'长笛',
    '61':'琵琶',
    '62':'手风琴',
    '63':'古筝',
    '64':'古琴',
    '65':'大提琴',
    '66':'打击乐',
    '67':'圆号',
    '68':'高等数学',
    '69':'网球',
    '70':'乒乓球',
    '71':'游泳',
    '72':'围棋',
    '73':'中国画',
    '74':'国际象棋',
    '75':'羽毛球',
    '76':'中国象棋',
    '77':'卡通画',
    '78':'书法',
    '79':'美术',
    '80':'跆拳道',
    '81':'空手道'
};
function getCourse(code) {
    return G_Course[code];
}

/**
 * parse Schdule info
 * "[11,12,13]"
 * @param schedule
 */
function pareSchedule(schedule) {
    if(schedule != "") {
        var ses = eval(schedule.replace("\"",''));
        var sarray = [];
        for(var s in ses) {
           sarray.push(getSchedule(ses[s]));
        }
        return sarray.join(', ');
    }
}
/**
 * 上课时间控件生成器
 * @param id  下拉框编号
 * @param empty 是否生成空值项
 * @param value 被选中的值
 */
function SelectSchedule(id, empty, value){
    var ele = $('#'+id);
    ele.text('');// clear the options of the select control
    if(empty == true) {
        $('<option/>').val("").text('请选择').appendTo(ele);
    }
    for(var s in Schedule) {
        $('<option/>').val(s).text(Schedule[s]).appendTo(ele);
    }
    if(value) {
        ele.val(value);
    }
}

/**
 * 生成地区选择下拉框
 * 参数是一个对象，这个对象包括了一下的项目
 * ct:放置下拉框的容器id,
 * p:要生成的省份的下拉框id(id=name)
 * c:要生成的城市的下拉框id(id=name)
 * d:要生成的地区的下拉框id(id=name)
 * ps:是否要生成一个请选择的选项
 * pv:省份下拉框选择的值（可选）
 * cv:城市下拉框选择的值（可选）
 * dv:地区下拉框选择的值（可选）
 * @param opts
 */
function SelectArea(opts){
    purl = path+'/area/get';
    var opt = {ct:'',p:'',c:'',d:'',pv:'',cv:'',dv:''};
    var container = $('#'+opts.ct);
    var province = $('<select/>').attr('id', opts.p).attr('name', opts.p);
    if(opts.ps) {
        $('<option/>').val('').text('请选择').appendTo(province);
    }
    var city = $('<select/>').attr('id', opts.c).attr('name', opts.c);
    var distinct = $('<select/>').attr('id', opts.d).attr('name', opts.d);

    container.append(province);

    var initProvince = function(p) {
        AjaxRequest(purl, {tp:0}, function(areas) {
            for (var i = 0; i < areas.length; i++) {
                $('<option />').attr('value', areas[i].c).text(areas[i].n).appendTo(p);
            }
            p.change(function(){
                var v = $(this).val();
                selArea(v, city, distinct);
            });
        });
    }

    var selArea = function(pv, c, d) {
        d.remove();
        if (pv != '') {
            AjaxRequest(purl, {tp:1, pid:pv}, function(areas) {
                c.text('');
                $('<option value="">请选择</option>').appendTo(c);
                for (var i = 0; i < areas.length; i++) {
                    $('<option />').attr('value', areas[i].c).text(areas[i].n).appendTo(c);
                }
                container.append(c);
                c.change(function() {
                    var v = $(this).val();
                    selDist(v, d);
                });
            });
        } else {
            c.remove();
        }
    }

    var selDist = function(cv, d) {
        d.remove();
        if (cv != '') {
            AjaxRequest(purl, {tp:2, pid:cv}, function(dists) {
                if(dists.length > 0) {
                    d.text('');
                    $('<option value="">请选择</option>').appendTo(d);
                    for (var i = 0; i < dists.length; i++) {
                        $('<option />').attr('value', dists[i].c).text(dists[i].n).appendTo(d);
                    }
                    container.append(d);
                } else {
                    d.remove();
                }
            });
        } else {
            d.remove();
        }
    }

    initProvince(province);

}